//
//  NSString+JTY.m
//  JTY_App
//
//  Created by cyf on 2025/3/29.
//

#import "NSString+JTY.h"
#import "RSA.h"

@implementation NSString (JTY)

// 去掉字符串两边的空格
-(NSString*)trim{
    return [self stringByTrimmingCharactersInSet:
            [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

//判断字符串是否为空(nil,Null,@"null",@"")
+(BOOL)emptyValidate:(NSString *)string{
    if (!string) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string trim] isEqualToString:@"null"]) {
        return YES;
    }
    if ([[string trim] isEqualToString:@"(null)"]) {
        return YES;
    }
    if ([[string trim] isEqualToString:@"<null>"]) {
        return YES;
    }
    if ([string trim].length == 0) {
        return YES;
    }
    return NO;
}
- (NSString *)removeFloatAllZero {
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(self.floatValue)];
    return outNumber;
}
- (CGSize)sizeForFont:(UIFont *)font size:(CGSize)size mode:(NSLineBreakMode)lineBreakMode {
    CGSize result;
    if (!font) font = [UIFont systemFontOfSize:12];
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMutableDictionary *attr = [NSMutableDictionary new];
        attr[NSFontAttributeName] = font;
        if (lineBreakMode != NSLineBreakByWordWrapping) {
            NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
            paragraphStyle.lineBreakMode = lineBreakMode;
            attr[NSParagraphStyleAttributeName] = paragraphStyle;
        }
        CGRect rect = [self boundingRectWithSize:size
                                         options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                      attributes:attr context:nil];
        result = rect.size;
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        result = [self sizeWithFont:font constrainedToSize:size lineBreakMode:lineBreakMode];
#pragma clang diagnostic pop
    }
    return result;
}
- (BOOL)isUrl {
    
    if(self == nil) {
        return NO;
    }
    
    NSString *url;
    if (self.length>4 && [[self substringToIndex:4] isEqualToString:@"www."]) {
        url = [NSString stringWithFormat:@"http://%@",self];
    }else{
        url = self;
    }
    NSString *urlRegex = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
    NSPredicate* urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegex];
    return [urlTest evaluateWithObject:url];
}
//验证手机号码
+ (NSString *)numberSuitScanf:(NSString*)number{

    //首先验证是不是手机号码

    NSString *MOBILE = @"^1+[345678]+\\d{9}";

    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];

    BOOL isOk = [regextestmobile evaluateWithObject:number];

    if (isOk) {//如果是手机号码的话
        NSString *numberString = [number stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        return numberString;
    }
    return number;
}
- (BOOL)isValidMobilePhoneNumber
{
    NSString *mobileNum = self;
    NSString *regexStr = @"^1[3|4|5|6|7|8|9][0-9]{9}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexStr];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES) {
        return YES;
    }
    return NO;
}
#pragma 正则匹配用户密码6-20位数字和字母组合
+ (BOOL)checkPassword:(NSString *) password
{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
    
}

#pragma 正则匹配用户姓名,20位的中文或英文
+ (BOOL)checkUserName : (NSString *) userName
{
    NSString *pattern = @"^[a-zA-Z\u4E00-\u9FA5]{1,20}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:userName];
    return isMatch;
    
}
+ (NSString *)changeDoubleToString:(double)d{
    NSString *dStr = [NSString stringWithFormat:@"%f", d];
    NSDecimalNumber *dn = [NSDecimalNumber decimalNumberWithString:dStr];
    return dn.stringValue;
}

+ (NSString *)stringDate{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
    return dateString;
}
+ (NSString *)rsaString:(NSString *)str{
    
    NSMutableString *publicKey = [NSMutableString stringWithString:@"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCY76i1gHm4SZyIlX/Wu0HJ6ex\n"];
    [publicKey appendString:@"XQ4UQmVAqM1ANqjQU857lvrpI3RGuM2F8swpCQyEfqxYCbIqYSf5z2/6c3c2bR1+\n"];
    [publicKey appendString:@"D3H1ZWfSVSV9hiwE5bzJiBcKYMGBAYHvz4qVB+rAYQ+hBc8lBHBvByth2c2JLzxJ\n"];
    [publicKey appendString:@"Kmvt9r0MruVmDA3L9wIDAQAB"];
    
//    NSMutableString *PRIVATE_KEY = [NSMutableString stringWithString:@"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMJjvqLWAebhJnIi\n"];
//    [PRIVATE_KEY appendString:@"Vf9a7Qcnp7FdDhRCZUCozUA2qNBTznuW+ukjdEa4zYXyzCkJDIR+rFgJsiphJ/nP\n"];
//    [PRIVATE_KEY appendString:@"b/pzdzZtHX4PcfVlZ9JVJX2GLATlvMmIFwpgwYEBge/PipUH6sBhD6EFzyUEcG8H\n"];
//    [PRIVATE_KEY appendString:@"K2HZzYkvPEkqa+32vQyu5WYMDcv3AgMBAAECgYEAkzIodvGKuyOekyqA6D4X4iUb\n"];
//    [PRIVATE_KEY appendString:@"DGkkch7cwRuRYKCDME1lu5xWHxgjwjHKHzX9ds1NVz78jiW5bfHn7XgwmPu6Nn41\n"];
//    [PRIVATE_KEY appendString:@"Rt4P14s41WGh9MMk/GJ0saI9OtQ2Ao6RNqUqfSMvOuCoWDE39CPkC26K00iRvoEQ\n"];
//    [PRIVATE_KEY appendString:@"+w0CgKdrS688eu0xQLECQQD69QfKWMDlh6INsn4M4U9ubV2N9r+FWWJKq0Gc0nHI\n"];
//    [PRIVATE_KEY appendString:@"xtbpdho6JYenJI460kO2twmFhmEWARaYcXh9TAQQ0JqdAkEAxku4dT67DPNoB9uK\n"];
//    [PRIVATE_KEY appendString:@"MVyfNFiicmjbnsSzy1xSpuKCPRCL3CzvFXNBv64UmQTTy22KBGazdlRh7am1Aoqr\n"];
//    [PRIVATE_KEY appendString:@"a7SiowJBALXFNzBUGtvl4vYC3BQeOjdk1ceW+t/ufyhQZQTe1PW1OEL/fT2yo0/o\n"];
//    [PRIVATE_KEY appendString:@"RXDLjapRZ38kdzvF7ATc44X1wlgfkG0CQBOcD1zA3FyWgZYtVsg04aWakk4AIp/b\n"];
//    [PRIVATE_KEY appendString:@"0e/tbFsGkVyak0otw2L6p+jdvTm4qX03kuuGgH7WL20CWF0s+3DGR0MCQQCO6Qo9\n"];
//    [PRIVATE_KEY appendString:@"0VuhduauOQsxARjCb4iDl7dB91BUOptnCqjzG2OhKF+nrIu923cI0vDgqTUmWY/o\n"];
//    [PRIVATE_KEY appendString:@"eCGtgqBwPdipKGCi"];
            
    if ([NSString emptyValidate:str]){
        return  [NSString string];
    }
//    NSString *encWithPrivKey = [RSA encryptString:str privateKey:PRIVATE_KEY];
    NSString *encWithPubKey = [RSA encryptString:str publicKey:publicKey];
    
    return  encWithPubKey;
    
}
+ (NSString *)getCurrentTime {
    //获取当前时间
    NSDate *now = [NSDate date];
//    NSLog(@" now date is: %@ ",now);
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    
    NSInteger year = [dateComponent year];
    NSInteger month = [dateComponent month];
    NSInteger day = [dateComponent day];
    NSInteger hour = [dateComponent hour];
    NSInteger minute = [dateComponent minute];
    NSInteger second = [dateComponent second];
    
//    NSLog(@" year is: %ld ",(long)year);
//    NSLog(@" month is: %ld ",month);
//    NSLog(@" day is: %ld ",day);
//    NSLog(@" hour is: %ld ",hour);
//    NSLog(@" minute is: %ld ",minute);
//    NSLog(@" second is: %ld ",second);
    
    NSString *weekString = [NSString weekStringFromDate:now];
    
    NSString *dateTime = [NSString getChineseCalendarWithDate:now];//[NSString LunarForSolarYear:(int)year Month:(int)month Day:day];
    
    NSString *currentTime = [NSString stringWithFormat:@"%ld-%ld-%ld%@ %@",year,month,day,weekString,dateTime];
    
    return currentTime;
}
+ (NSString *)weekStringFromDate:(NSDate *)date{

    NSArray *weeks=@[[NSNull null],@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];

    NSCalendar *calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSTimeZone *timeZone=[[NSTimeZone alloc]initWithName:@"Asia/Beijing"];

    [calendar setTimeZone:timeZone];

    NSCalendarUnit calendarUnit=NSCalendarUnitWeekday;

    NSDateComponents *components=[calendar components:calendarUnit fromDate:date];

    return [weeks objectAtIndex:components.weekday];

}

+(NSString*)getChineseCalendarWithDate:(NSDate *)date{
 
      NSArray *chineseYears = [NSArray arrayWithObjects:
 
                         @"甲子", @"乙丑", @"丙寅", @"丁卯",  @"戊辰",  @"己巳",  @"庚午",  @"辛未",  @"壬申",  @"癸酉",
 
                         @"甲戌",   @"乙亥",  @"丙子",  @"丁丑", @"戊寅",   @"己卯",  @"庚辰",  @"辛己",  @"壬午",  @"癸未",

                        @"甲申",   @"乙酉",  @"丙戌",  @"丁亥",  @"戊子",  @"己丑",  @"庚寅",  @"辛卯",  @"壬辰",  @"癸巳",

                        @"甲午",   @"乙未",  @"丙申",  @"丁酉",  @"戊戌",  @"己亥",  @"庚子",  @"辛丑",  @"壬寅",  @"癸丑",

                        @"甲辰",   @"乙巳",  @"丙午",  @"丁未",  @"戊申",  @"己酉",  @"庚戌",  @"辛亥",  @"壬子",  @"癸丑",

                        @"甲寅",   @"乙卯",  @"丙辰",  @"丁巳",  @"戊午",  @"己未",  @"庚申",  @"辛酉",  @"壬戌",  @"癸亥", nil];

     NSArray *chineseMonths=[NSArray arrayWithObjects:

                         @"正月", @"二月", @"三月", @"四月", @"五月", @"六月", @"七月", @"八月",

                         @"九月", @"十月", @"冬月", @"腊月", nil];


     NSArray *chineseDays=[NSArray arrayWithObjects:

                       @"初一", @"初二", @"初三", @"初四", @"初五", @"初六", @"初七", @"初八", @"初九", @"初十",

                       @"十一", @"十二", @"十三", @"十四", @"十五", @"十六", @"十七", @"十八", @"十九", @"二十",

                       @"廿一", @"廿二", @"廿三", @"廿四", @"廿五", @"廿六", @"廿七", @"廿八", @"廿九", @"三十",  nil];

    NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];


    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;

    NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:date];

//    NSLog(@"%ld_%ld_%ld  %@",(long)localeComp.year,(long)localeComp.month,(long)localeComp.day, localeComp.date);



     NSString *y_str = [chineseYears objectAtIndex:localeComp.year-1];

     NSString *m_str = [chineseMonths objectAtIndex:localeComp.month-1];

     NSString *d_str = [chineseDays objectAtIndex:localeComp.day-1];



//     NSString *chineseCal_str =[NSString stringWithFormat: @"%@_%@_%@",y_str,m_str,d_str];
    NSString *chineseCal_str =[NSString stringWithFormat: @"农历%@%@",m_str,d_str];


     return chineseCal_str;

}


//获取当前的时间
+(NSString*)getCurrentTimeWithEndTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:@"YYYY-MM-dd"];
    //现在时间,你可以输出来看下是什么格式
    NSDate *datenow = [NSDate date];
    //----------将nsdate按formatter格式转成nsstring
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    NSString *endTimeString = [NSString stringWithFormat:@"%@ 23:59:59",currentTimeString];
     NSLog(@"currentTimeString = %@",currentTimeString);
     return endTimeString;
}
//获取当前的时间一周前时间
+(NSString *)getCurrentTimeWithStartTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    // 创建一个日期格式化器
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; // 设置日期格式

    // 将时间字符串转换为日期对象
    NSString *dateString = [NSString getCurrentTimeWithEndTime];
    NSDate *date = [dateFormatter dateFromString:dateString];

    // 获取时间戳（以秒为单位）
    NSTimeInterval timestamp = [date timeIntervalSince1970];
    timestamp = timestamp - 60*60*24*8 + 1 ;
    // 将时间戳转换为日期对象
    NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:timestamp];

//    // 创建一个日期格式化器
//    NSDateFormatter *startDateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; // 设置日期格式
    // 将日期对象转换为时间字符串
    NSString *startDateString = [dateFormatter stringFromDate:startDate];
    
    
    return startDateString;
}

@end
